package com.example.web;


import jdk.internal.util.xml.impl.Input;
import lombok.extern.slf4j.Slf4j;
import net.sf.jsqlparser.expression.TryCastExpression;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import sun.jvm.hotspot.runtime.Bytes;

import javax.servlet.http.HttpServletResponse;
import java.io.*;

@Controller
@Slf4j
public class FileController {
    /**
     *
     * @param uploadFile  上传过来文件封装的对象，包含了上传文件所有信息
     * @return
     */
    @RequestMapping("/upload")
    public String upload(MultipartFile uploadFile, Model model) throws Exception {
        int a = 10/0;
        log.info("进入FileController的upload方法，参数：{}======>"+uploadFile);
        //1.获取文件名
        String oldFileName = uploadFile.getOriginalFilename();//1.jpg
        //2.上传
        File dir =  new File("/Users/mac/Documents/upload");

        File file = new File(dir,"/"+oldFileName);///Users/mac/Documents/upload/1.jpg
        uploadFile.transferTo(file);
        //3.返回model和view
        model.addAttribute("filename",oldFileName);
        return "pic_list";
    }

    @RequestMapping("/download")
    public void download(HttpServletResponse response,String filename) throws IOException {
        //1.从服务器的磁盘中读取客户要下载的文件：io流？？？？？
        File dir =  new File("/Users/mac/Documents/upload");
        File file = new File(dir,"/"+filename);  //读入写出


        long length = file.length();//获取文件大小
        InputStream inputStream =new FileInputStream(file);
        byte[] bytes = new byte[(int)length];
        int rows = inputStream.read(bytes);

        //2.通过tomcat将文件io输出到客户端
        OutputStream outputStream = response.getOutputStream();
        //设置响应的minaType
        //写之前设置响应流以附件的形式打开返回值,这样可以保证前边打开文件出错时异常可以返回给前台
        response.setHeader("Content-Disposition","attachment;filename="+filename);
        outputStream.write(bytes);
        outputStream.flush();
        outputStream.close();


    }

}
